import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, Card, message, Tag } from 'antd';
import { UserOutlined, LockOutlined, GlobalOutlined, SmileOutlined } from '@ant-design/icons';
import Particles from 'react-tsparticles';
import { loadFull } from 'tsparticles';
import { options } from '@/utils/tsparticles.Options';
import { http } from '@/utils/http';
import './index.scss';
const { Grid } = Card;

export default function Login() {
  const navigate = useNavigate();
  const onFinish = values => {
    console.log(values);
    http
      .get(`/users?username=${values.username}&password=${values.password}&roleState=true&_expand=role`)
      .then(res => {
        // data无长度，登录失败
        if (!res.data.length) {
          message.error('登录失败！', 2);
        } else {
          window.sessionStorage.setItem('news', JSON.stringify(res.data[0]));
          navigate('/');
          message.open({
            content: (
              <div>
                <SmileOutlined
                  style={{
                    color: '#108ee9',
                  }}
                />
                欢迎来到在线IT新闻发布管理系统！
              </div>
            ),
            duration: 2,
          });
          message.open({
            content: <Tag color='volcano'>退出登录：command + k / ctrl + k</Tag>,
            duration: 2.5,
          });
        }
      })
      .catch(() => {
        message.error('request失败！', 2);
      });
  };
  return (
    <div
      className='login'
      style={{
        backgroundColor: 'rgb(35,39,65)',
        height: '100%',
        display: 'flex',
      }}>
      <Particles init={async main => loadFull(main)} options={options} />
      {/* 登录框 */}
      <Grid className='login-container' hoverable>
        {/* 图标div */}
        <div className='global-outlined'>
          <GlobalOutlined spin />
          <span id='login-title'>新闻发布管理系统</span>
        </div>

        <Form name='normal_login' className='login-form' onFinish={onFinish}>
          <Form.Item
            name='username'
            rules={[
              {
                required: true,
                message: '请输入用户名！',
              },
            ]}>
            <Input autoFocus prefix={<UserOutlined className='site-form-item-icon' />} placeholder='admin' />
          </Form.Item>
          <Form.Item
            name='password'
            rules={[
              {
                required: true,
                message: 'Please input your Password!',
              },
            ]}>
            <Input prefix={<LockOutlined className='site-form-item-icon' />} type='password' placeholder='123' />
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit' className='login-form-button'>
              Log in
            </Button>
          </Form.Item>
        </Form>
      </Grid>
    </div>
  );
}
